package com.shuiyun.jdbc.sharding;

import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.util.Collection;
import java.util.LinkedHashSet;

/**
 * @author shuiyun
 */
public class OrderRangeShardingTable implements RangeShardingAlgorithm<Long> {


    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<Long> shardingValue) {
        Collection<String> result = new LinkedHashSet<>(availableTargetNames.size());
        // 获取原始表名
        String logicTableName = shardingValue.getLogicTableName();
        // 获取范围值
        Range<Long> valueRange = shardingValue.getValueRange();
        long start = valueRange.lowerEndpoint();
        long end = valueRange.upperEndpoint();
        for (long i = start;i<= end; i++){
            long value = i % 2 + 1;
            if (availableTargetNames.contains(logicTableName+"_"+value)){
                result.add(logicTableName+"_"+value);
            }
        }
        return result;
    }
}
